package com.lifang.imsoa.base.controller;

import com.leo.jackson.JsonTool;
import com.lifang.imsoa.model.response.BusinessException;
import com.lifang.imsoa.util.StringUtil;
import com.lifang.imsoa.util.SystemUtil;
import com.lifang.model.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

@Component
@Slf4j
public class BaseController {
	protected String writeValueAsString(Object obj) {
		Response response = new Response();
		response.setStatus(1);
		response.setMessage("成功");
		response.setData(obj);
		return JsonTool.writeValueAsString(response);
	}

	protected String writeValueAsString4Response(Response response) {
		return JsonTool.writeValueAsString(response);
	}
	
	/**
	 * @date 2014年10月27日 下午7:04:39
	 * @description  
	 * 将UUID 做为key，系统时间做为value，加入到Memcached中，缓存30分钟
	 */
	public String getToken() {
		return StringUtil.getrandomUUID();
	}
	
	protected void responseWrite(HttpServletRequest request, HttpServletResponse response) {
		responseWrite(request, response);
	}

	@ExceptionHandler(Throwable.class)
	@ResponseBody
	public Response handleIOException(Throwable e, Locale locale, HttpServletRequest req, HttpServletResponse resp) {
		if (e instanceof BusinessException) {
			log.info("BusinessException in \n " + ((BusinessException) e).getStatus() + ":" + ((BusinessException) e).getMessage());
		} else {
			log.info("Exception in " + e.getMessage(), e);
		}
		return this.writeError(req, resp, e);
	}

	private Response writeError(HttpServletRequest req, HttpServletResponse resp, Throwable e) {
		Response html = new Response();
		if (e instanceof BusinessException) {
			BusinessException businessException = (BusinessException) e;

			html.setStatus(businessException.getStatus());
			html.setMessage(businessException.getMessage());
		} else {
			html.setStatus(-1);
			html.setMessage("网络不给力，请稍候再试");
		}
		return html;
	}
	
	
	protected void responseWrite(Object result, HttpServletRequest request, HttpServletResponse response) {
		Response returnObj = new Response();
		returnObj.setStatus(1);
		returnObj.setMessage("成功");
		returnObj.setData(result);
		SystemUtil.writeResponse(request, response, JsonTool.writeValueAsString(returnObj));
	}
	
}
